<?php
//Search

//** Each page that is "stand alone" must have this variable.
$authorizedPage = true; 
require('config.php');

sanitize($_GET['search']);

$search = "%".strtolower(trim($_GET['search'])) . "%";
$searchClean = strtolower(trim($_GET['search']));

echo $search;

$searchResults = Array();
if(strlen($search) == 2) die();

$query = "SELECT id, tags, title, steps, ingredients, materials, description FROM recipie WHERE LOWER(steps) LIKE '$search' OR LOWER(ingredients) LIKE '$search' OR LOWER(materials) LIKE '$search' OR LOWER(tags) LIKE '$search' OR LOWER(title) LIKE '$search' OR LOWER(description) LIKE '$search'";
$results = mysql_query($query) or die(mysql_error());


function matches($string, $search,$offset=0){
	$position = stripos($string, $search, $offset);
	echo $search;
	if($position === FALSE) return 0;
	return 1 + matches($string, $search, $position + strlen($search));
}

function weightSort(Array $a, Array $b){
	if($a['weight'] == $b['weight']) return 0;
	return ($a['weight'] < $b['weight']) ? -1 : 1;
}

$index = 0;
while($row = mysql_fetch_assoc($results)){
	echo '<br />match';
	$searchResults[$index]['recipieID'] = $row['id'];
	$searchResults[$index]['title'] = $row['title'];
	
	$weight = 0;
	$weight += matches($row['steps'], $searchClean);
	$weight += matches($row['ingredients'], $searchClean);
	$weight += matches($row['materials'], $searchClean);
	$weight += matches($row['description'], $searchClean);
	$weight += matches($row['title'], $searchClean);
	$weight += matches($row['tags'], $searchClean);
	
	echo '<br />' . $row['id'] . ' weight ' . $weight;
		
	$searchResults[$index]['weight'] = $weight;
	
	$index++;
}

echo '<br />';
print_r($searchResults);
echo '<br />';
usort($searchResults, "weightSort");
print_r($searchResults);

?>